'use client';
import Image from 'next/image';
import { useEffect, useState, useRef, memo } from 'react';
import noVideo from '@/img/wms/noVideo.png';
import styles from '../../pages.module.scss';

const palyPath = `${process.env.NEXT_PUBLIC_OSS_URL}/module/PlayerControl.js`;
const wsPath = process.env.NEXT_PUBLIC_WSS_URL;

const DHPlayer = (props: {warehouseMontiorInfo: any, cameraList: any }) => {
  const [hasVideo, setHasVideo] = useState(false);
  const timer = useRef<any>();

  const playVideo = () => {
    const info = props.warehouseMontiorInfo;
    const cameraNetworkAddress = props.cameraList?.[0]?.cameraNetworkAddress;
    const options = {
      wsURL: wsPath,
      // rtspURL: `rtsp://video-wms.zmetaport.com:17718/cam/realmonitor?channel=22&subtype=1&proto=Private3`,
      rtspURL: `${info?.monitorServerAddr}${cameraNetworkAddress}&proto=Private3`,
      username: info?.monitorServerAccount,
      password: info?.monitorServerPassword,
      lessRateCanvas: true,
      playback: false,
      isPrivateProtocol: false,
    };
    if (typeof window !== 'undefined') {
      const player = new (window as any).PlayerControl(options);

      const canvas = document.getElementById('testCanvas');
      const video = document.getElementById('testVideo');

      player.on('PlayStart', function (e: any) {
        setHasVideo(true);
      });

      player.on('FrameTypeChange', function (e: any) {
        // console.log('FrameTypeChange: ' + e);
      });
      player.on(
        'Error',
        function (err: { errorCode: number; description: string }) {
          setHasVideo(false);
          if (timer.current) {
            clearTimeout(timer.current);
          }
          timer.current = setTimeout(() => {
            playVideo();
          }, 3000);
        },
      );

      player.on('WorkerReady', function () {
        player.connect();
      });

      player.init(canvas, video);
    }
  };

  useEffect(() => {
    const script = document.createElement('script');
    script.src = palyPath;
    script.onload = () => {
      playVideo();
    };
    document.body.appendChild(script);
  }, []);

  return (
    <div className={styles.playerBox}>
      <div
        id="ezuikit-player"
        style={{
          backgroundColor: '#000',
          width: '100%',
          height: 425,
          borderRadius: 10,
        }}
      ></div>
      {!hasVideo && (
        <Image
          src={noVideo}
          style={{
            position: 'absolute',
            width: '100%',
            height: 425,
            borderRadius: 10,
            left: 0,
            top: 0,
          }}
          alt="noVideo"
        />
      )}
    </div>
  );
};

export default memo(DHPlayer);
